#-*- coding: utf-8 -*-
#  Copyright 2011-2013 wuweihui@cn.ibm.com
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import unittest
from types import InstanceType

def read_test_cases(casemodule):
   """
   input: Case module name
   output: { Module.CaseName : [Test case list] }
   """
   case_list = []
   cmd = '__import__("%s")' % (casemodule)
   testmodule = eval(cmd)
   for mod in dir(testmodule):
      if not mod.startswith('_') and isinstance(testmodule.__getattribute__(mod), type(unittest)):
         #print mod
         testcase = testmodule.__getattribute__(mod)
         for attr in dir(testcase):
            if not attr.startswith('_') \
            and isinstance(testcase.__getattribute__(attr), type)\
            and issubclass(testcase.__getattribute__(attr), unittest.TestCase):
               case_list.append(testcase.__getattribute__(attr))
   return case_list

def read_test_methods(testcase):
   return [c._testMethodName for c in unittest.TestLoader().loadTestsFromTestCase(testcase)]

def gen_test_suite(casedict):
   """
   read test cases from a dict type value:
   {TestModule1.TestCase1:[TestMethod1, TestMethod2],
    TestModule2.TestCase1:[TestMethod1, TestMethod2],
   }
   """
   suitelist = []
   for k, v in casedict:
      if v:
         suitelist.append(unittest.TestSuite(map(k, v)))
   return unittest.TestSuite(suitelist)

def run_suite(suite):
   unittest.TextTestRunner(verbosity=2).run(suite)

if __name__ == '__main__':
   for case in read_test_cases():
      print case.__name__, case
      
   print dir(case)
   cases = unittest.TestLoader().loadTestsFromTestCase(case)
   print cases
   print dir(cases)
   for c in cases:
      print c._testMethodName, c.__class__.__name__
   print dir(c)
   print type(c)
   print c._testMethodName
   methods = read_test_methods(case)
   print methods